//
//  ERBaseViewController.m
//  ExchangeRate
//
//  Created by 方义强 on 15/11/7.
//  Copyright © 2015年 方义强. All rights reserved.
//

#import "ERBaseViewController.h"
#import "Reachability.h"
#import "ERCountryJsonModel.h"
#import "NSString+Characters.h"
#import "ERResourceModel.h"
// Numerics
CGFloat const kTWMesssageBarDemoControllerButtonPadding = 10.0f;
CGFloat const kTWMesssageBarDemoControllerButtonHeight = 50.0f;

// Colors
static UIColor *kTWMesssageBarDemoControllerButtonColor = nil;

@interface ERBaseViewController ()
@property (nonatomic, strong) NSArray *jsonFileNameArr;
@property (nonatomic, strong) NSString *prefixStr;
@property (nonatomic, assign) BOOL isChoice;
@property (nonatomic, strong) NSMutableArray *subStrArr;

@property (nonatomic, assign) NSInteger num;

@end

@implementation ERBaseViewController
#pragma mark - Alloc/Init

+ (void)initialize
{
    if (self == [ERBaseViewController class])
    {
        kTWMesssageBarDemoControllerButtonColor = [UIColor colorWithWhite:0.0 alpha:0.25];
    }
}

- (id)initWithStyleSheet:(NSObject<TWMessageBarStyleSheet> *)stylesheet
{
    self = [super init];
    if (self)
    {
        [TWMessageBarManager sharedInstance].styleSheet = stylesheet;
    }
    return self;
}

- (id)init
{
    return [self initWithStyleSheet:nil];
}

- (UIView *)topView
{
    if (!_topView)
    {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, kSCREENWIDTH, kTopViewHeight)];
        _topView.backgroundColor = [UIColor whiteColor];
        
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopViewHeight - 1, kSCREENWIDTH, 1)];
        _lineView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.9];
        [_topView addSubview:_lineView];
        
        _leftButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _leftButton.frame = CGRectMake(10, 0, 100, 50);
        _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        _leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _leftButton.titleLabel.font = [UIFont fontWithName:@"STHeitiK-Light" size:13];
        [_topView addSubview:_leftButton];
        
        _rightButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _rightButton.frame = CGRectMake(kSCREENWIDTH - 50, 0, 50, 50);
        _rightButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        
        [_topView addSubview:_rightButton];
        
        [_topView addSubview:self.titleLabel];
        [self.view addSubview:_topView];
        
    }
    return _topView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kSCREENWIDTH / 2 - 80, 10, 160, kTopViewHeight - 20)];
        _titleLabel.text = NSLocalizedString(@"极简汇率", nil);
        _titleLabel.font = [UIFont fontWithName:@"STHeitiK-Light" size:15];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    return _titleLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isChoice = NO;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self openDataBase];
        [self copyJsonFileManager];
    });
    // Do any additional setup after loading the view.
    NSLog(@"%@", self.topView);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLangure:) name:@"Appdelegate" object:@"ChangeLangure"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choiceLangure:) name:@"chang" object:@"change"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 返回当前网络状态
- (int)currentNetWork
{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reachability currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"无网络连接");
            [self topAlertShowTitle:@"ERROR" andMessage:NSLocalizedString(@"当前无网络，请检查！", nil) andType:(TWMessageBarMessageTypeError)];
            return 0;
            break;
            
        case ReachableViaWiFi:
            NSLog(@"wifi在线");
            return 1;
            break;
            
        case ReachableViaWWAN:
            NSLog(@"3G在线");
            return 2;
            break;
    }
}

#pragma mark 打开数据库
- (void) openDataBase
{
    NSString *documentPath = [self getDocumentPath:@"ExchangeRateData.sqlite"];
    _dataBase = [FMDatabase databaseWithPath:documentPath];
    
    if ([_dataBase open]) {
        NSLog(@"打开数据库成功");
        [_dataBase executeUpdate:@"create table ERData(name text, price text, symbol text primary key, ts text, type text, utctime text, volume text, isSelected text, isLocation text);"];
        [_dataBase executeUpdate:@"create table ERShowData(name text, price text, symbol text primary key, ts text, type text, utctime text, volume text, isSelected text, isLocation text);"];
    }
    else NSLog(@"数据库打开失败");
}

#pragma mark 获取沙河路径
- (NSString *) getDocumentPath:(NSString *)fileName
{
    return [[NSSearchPathForDirectoriesInDomains(9, 1, 1)firstObject] stringByAppendingPathComponent:fileName];
}

#pragma mark 返回json当前路径
- (NSString *) getJsonPath:(NSString *)fileName
{
    return [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
}

#pragma mark 将jsno数据拷贝到document 调用
- (void) copyJsonFileManager
{
    _jsonFileNameArr = @[@"CountriesGeoCode.json", @"currency.json", @"currency_rate.json"];
    for (NSString *fileName in _jsonFileNameArr) {
        [self copyJsonDataToDocument:fileName];
    }
}

#pragma mark 将jsno数据拷贝到document
- (void) copyJsonDataToDocument:(NSString *)fileName
{
    NSString *filePath = [self getJsonPath:fileName];
    NSString *docPath = [self getDocumentPath:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager contentsAtPath:docPath]) {
        
    }
    else
    {
        [fileManager copyItemAtPath:filePath toPath:docPath error:nil];
    }
    if ([fileName isEqualToString:_jsonFileNameArr[1]]) {
        [self analyzeForJson:fileName];
    }
}

#pragma mark 进行json 解析
- (void) analyzeForJson:(NSString *)fileName
{
    _dataCountryArr = [NSMutableArray arrayWithCapacity:0];
    [_dataCountryArr removeAllObjects];
    NSString *filePath = [self getDocumentPath:fileName];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    _jsonDataArr = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
    for (NSDictionary *dic in _jsonDataArr) {
        ERCountryJsonModel *model = [[ERCountryJsonModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [_dataCountryArr addObject:model];
    }
    [self subStringOfJsonCountry];
    [self divideForSection];
}

#pragma mark 截取子字符串
- (void) subStringOfJsonCountry
{
    _subStrArr = [NSMutableArray arrayWithCapacity:0];
    NSArray *array = [_jsonDataArr[0] allKeys];
    for (NSString *str in array) {
        if ([str containsString:@"currency_name_"]) {
            [_subStrArr addObject:[str substringFromIndex:14]];
        }
    }
    NSLog(@"%@", _subStrArr);
}

#pragma mark 根据当前手机的类型 进行section划分
- (void) divideForSection
{
    _dataSectionArr = [NSMutableArray arrayWithCapacity:0];
    [_dataSectionArr removeAllObjects];
    NSString *currentLangure = [self getPreferredLanguage];
    if (!_isChoice) {
        for (NSString *country in _subStrArr) {
            if ([currentLangure containsString:country]) {
                if ([country isEqualToString:@"ja"] || [country isEqualToString:@"ko"]) {
                    _prefixStr = [NSString stringWithFormat:@"section_%@", country];
                }
                else _prefixStr = [NSString stringWithFormat:@"currency_name_%@", country];
                _counSim = country;
            }
        }
    }
    for (NSDictionary *dic in _jsonDataArr) {
        if ([currentLangure containsString:@"zh-Hant"] || [currentLangure containsString:@"zh-Hans"])
        {
            if ([[dic objectForKeyedSubscript:_prefixStr] length] > 0) {
                _num ++;
                [_dataSectionArr addObject:[[dic objectForKeyedSubscript:_prefixStr] firstCharacterOfName]];
            }
        }
        else if ([currentLangure containsString:@"ko"] || [currentLangure containsString:@"ja"])
        {
            [_dataSectionArr addObject:[dic objectForKey:_prefixStr]];
        }
        else [_dataSectionArr addObject:[[dic objectForKey:_prefixStr] substringWithRange:NSMakeRange(0, 1)]];
        
    }
    _dataSectionArr = [self clearArr:_dataSectionArr];
    _dataSectionArr = [self sortOfSection:_dataSectionArr];
    [self saveCountrySimpleInArr:_dataSectionArr];
}

#pragma mark 进行多于字符串清除
- (NSMutableArray *) clearArr:(NSMutableArray *)array
{
    NSMutableArray *resultArr = [NSMutableArray arrayWithCapacity:0];
    [resultArr removeAllObjects];
    for (NSString *section in array) {
        if ([resultArr containsObject:section]) {
            
        }
        else [resultArr addObject:section];
    }
   // [resultArr addObject:@"#"];
   // [resultArr addObject:@"$"];
    return resultArr;
}

#pragma mark 字符串排序
- (NSMutableArray *) sortOfSection:(NSMutableArray *)array
{
    NSArray *arr = nil;
    if ([_prefixStr containsString:@"ko"]) {
        arr = @[@"ㄱ", @"ㄴ", @"ㄷ", @"ㄹ", @"ㅁ", @"ㅂ", @"ㅅ", @"ㅇ", @"ㅈ", @"ㅎ"];
    }
    else if ([_prefixStr containsString:@"ja"])
    {
         arr = @[ @"&", @"C", @"あ", @"か", @"さ", @"た", @"な", @"は", @"ま", @"や", @"ら"];
    }
    else
    {
        arr = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            if (obj1 > obj2) {
                return NSOrderedDescending;
            }
            if (obj1 < obj2) {
                return NSOrderedAscending;
            }
            return NSOrderedSame;
        }];

    }
    return [NSMutableArray arrayWithArray:arr];
}

#pragma mark 调用顶部弹框方法
- (void)topAlertShowTitle:(NSString *)title andMessage:(NSString *)message andType:(TWMessageBarMessageType)type
{
    [[TWMessageBarManager sharedInstance] showMessageWithTitle:title description:message type:type];
}

#pragma mark 获取当前系统语言
- (NSString*)getPreferredLanguage

{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];

    return preferredLang;
}

#pragma mark 创建数组
- (NSMutableDictionary *) createDict
{
   
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    for ( NSString *section in _dataSectionArr) {
        NSMutableArray *everArr = [NSMutableArray arrayWithCapacity:0];
        [dic setObject:everArr forKey:section];
    }
    return dic;
}

#pragma mark 根据系统当前的版本将排序好的国家简称存入数组
- (void) saveCountrySimpleInArr:(NSMutableArray *)charArr
{
    _allNameDic = [NSMutableDictionary dictionaryWithDictionary:[self createDict]];
    _allSimDic = [NSMutableDictionary dictionaryWithDictionary:[self createDict]];
    NSString *first = nil;
    NSString *currentLangure = [self getPreferredLanguage];
    NSString *nameStr = [NSString stringWithFormat:@"currency_name_%@", _counSim];
    for (NSDictionary *dic in _jsonDataArr) {
            if ([currentLangure containsString:@"zh-Hant"] || [currentLangure containsString:@"zh-Hans"])
            {
                if ([[dic objectForKey:_prefixStr] length] > 0) {

                    first = [[dic objectForKey:_prefixStr] firstCharacterOfName];
                    _num ++;
                    [[_allSimDic valueForKey:first] addObject:dic[@"symbol"]];
                    [[_allNameDic valueForKey:first] addObject:[dic objectForKey:nameStr]];
                }
            }
            else if ([currentLangure containsString:@"ko"] || [currentLangure containsString:@"ja"])
            {
                first = dic[_prefixStr];
                [[_allSimDic valueForKey:first] addObject:dic[@"symbol"]];
                [[_allNameDic valueForKey:first] addObject:[dic objectForKey:nameStr]];
            }
            else
            {
                 first = [dic[_prefixStr] substringWithRange:NSMakeRange(0, 1)];
                 [[_allSimDic valueForKey:first] addObject:dic[@"symbol"]];
                 [[_allNameDic valueForKey:first] addObject:[dic objectForKey:nameStr]];
            }
    }
    _dataSimCounArr = [NSMutableArray arrayWithArray:[_allSimDic allValues]];
    _dataCounNameArr = [NSMutableArray arrayWithArray:[_allNameDic allValues]];
    [self saveNameSimForGJS];
}

#pragma mark 贵金属存储
- (void) saveNameSimForGJS
{
    NSString *nameStr = [NSString stringWithFormat:@"currency_name_%@", _counSim];
    NSArray *array = @[@"XAU", @"XAG", @"XPT"];
    NSMutableArray *nameArr = [NSMutableArray arrayWithCapacity:0];
    for (NSString *sym in array) {
        for (NSDictionary *dic in _jsonDataArr) {
            if ([dic[@"symbol"] isEqualToString:sym]) {
                [nameArr addObject:dic[nameStr]];
            }
        }
    }
    [_allNameDic setObject:nameArr forKey:@"$"];
    [_allSimDic setObject:array forKey:@"$"];
    [_dataSectionArr insertObject:@"$" atIndex:0];
}

#pragma mark - Orientation
 #pragma mark ------------顶部弹框方法 不准动--------------
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait); // pre-iOS 6 support
}

- (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
#pragma mark -------------------------------------------

#pragma mark 进行edit状态改变
- (NSMutableArray *)changeEditStye:(NSMutableArray *)array andValue:(BOOL)value andSimpleName:(NSString *)simName
{
    NSMutableArray *commArr = [self getCommentShowSim];
    for ( NSArray *eveArr in array) {
        for (ERResourceModel *model in eveArr) {
            if ([model.fields.symbol containsString:simName]) {
                model.isEdit= value;
            }
            else model.isEdit = 0;
            NSString *str = model.fields.symbol;
            NSString *name = [str substringWithRange:NSMakeRange(0, str.length - 2)];
            if ([commArr containsObject:name]) {
                model.fields.isSelected = 1;
            }
            else model.fields.isSelected = 0;
        }
    }
    return array;
}

#pragma mark 取显示国家的简写
- (NSMutableArray *) getCommentShowSim
{
    FMResultSet *result= [self.dataBase executeQueryWithFormat:@"select *from ERShowData"];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    while ([result next]) {
        NSString *str = [result stringForColumn:@"symbol"];
        NSString *name = [str substringWithRange:NSMakeRange(0, str.length - 2)];
        [array addObject:name];
    }
    return array;
}

#pragma mark 接受通知进行改变语言
- (void) changeLangure:(NSNotification *)notification
{
    _isChoice = NO;
    [self divideForSection];
}

- (void) choiceLangure:(NSNotification *)notification
{
    _counSim = notification.userInfo[@"lan"];
    _isChoice = YES;
    [self divideForSection];
    //_reload();
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
